<?php
namespace app\api\service;

/**
 * @name: 客户端登陆
 * @Param: 
 * @Description: 
 * @Author: foo
 * @Date: 2019-12-07 14:05:58
 */
use app\asmpasync\service\Wipf;
use app\common\service;
use app\common\system\SystemConfigService;
use app\common\wipf\WipfConfig;
use app\common\wipf\WipfRuleService;
use Wipf\Rule;
use Wipf\WipfRules;


class Login extends Base
{

    public $host_id = 0;//主机id
    public $group_id = 0;//主机所属用户组id
    public $poxy_ip = '';//代理主机ip
    public $poxy_port = 0;//模块主机端口
    public $module_ip = '';//代理主机ip
    public $module_port = 0;//模块端口

    /**
     * @name: 数据返回
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-09 14:24:27
     */
    function requestData ($data, $module)
    {
        $this->getHostId($data['hostkey']);

        if(!$this->checkModule($module))
        {
            return [];
        }

        $this->getModuleConnect($module);
        $this->getPoxyConnect();



        $config['modules_name'] = $module;
        $config['host_id'] = $this->host_id;
        $config['proxy_ip'] = $this->poxy_ip;
        $config['proxy_port'] = (int) $this->poxy_port;
        $config['modules_ip'] = $this->module_ip;
        $config['modules_port'] =(int) $this->module_port;

        $return = $this->toDo($module, [$data]);


        $merge = array_merge($config, $return);

        $this->toDo('updateVersion', [$module, $data['version']]);//更新 客户端/模块 版本

        return $merge;
        
    }
    /**
     * @name: 客户端登陆
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-07 14:06:23
     */
    function client ($hostData)
    {

        $HostModuleRelation = new service\HostModuleRelation();
        
        $config = $HostModuleRelation->findByHostId($this->host_id);

        if(empty($config))
        {
            $this->setError($this->CODE_FAIL, '未找到主机配置');
            return false;
        }

        $data = array_slice($config, 3);

        $return['config'] = [];
        foreach ($data as $k => $v)
        {
            $return[] = [
                'Name' => $k,
                'Enable' => $v ? true : false,
            ];
        }


        //修改主机信息
        if(
            isset($hostData['hostname']) &&
            isset($hostData['ip']) &&
            !empty($hostData['hostname']) &&
            !empty($hostData['ip'])
        )
        {

            $ip = implode(',', $hostData['ip']);
            $hostName = $hostData['hostname'].'('.$ip.')';

            db('host')->where('key', $hostData['hostkey'])
                ->update(['ip' => $ip, 'name' => $hostName]);
        }


        
        return $return;
    }


    /**
     * @name: 函谷盾 登陆接口
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-07 15:11:05
     */
    function wipf()
    {
        //获取防火墙默认处理方式
        $ConfigService = new SystemConfigService();
        $defaultProcess = $ConfigService->firewallDefaultHandle();

        //wipf配置
        $WipfConfig = new WipfConfig($this->host_id);
        $return['config'] = $WipfConfig->clientConfig($defaultProcess);

        //查询所有主机规则
        $RuleService = new WipfRuleService($this->host_id, $defaultProcess);
        $return['rules'] = $RuleService->allRule($WipfConfig->config_data);

        return $return;
    }

    /**
     * @name 主动防御登录接口
     * @author wx
     * @date 2020/6/22 10:55
     */
    function defense()
    {
        $configData = db('host_status')->where('host_id', $this->host_id)->find();

        if(empty($configData))
        {
            $this->setError($this->CODE_FAIL, '未找到主动防御设置!!');
            return false;
        }

        $levelArray = array(
            1 => 'hight',
            2 => 'mid',
            3 => 'low',
        );

        $boolArray = array(
            0 => false,
            1 => true
        );

        $return['config'] = array(
            'procstatus' => $boolArray[$configData['auto_defense']],
            'adstatus' =>  $boolArray[$configData['shell_defense']],
            'admode' =>  $boolArray[$configData['shell_defense_handle']],
            'adlevel' => $levelArray[$configData['shell_defense_level']],
            'tpstatus' =>  $boolArray[$configData['illegal_modify']],
            'tpdeformity' =>  $boolArray[$configData['file_safe']],
            'ppstatus' =>  $boolArray[$configData['empowerment']],
        );

        $modifyRuleData = $modifyExclueRuleData = $defenseRuleData = $defenseExclueRuleData = array();


        //放篡改规则
        $modifyRule = db('ips_website_protect')
            ->where('host_id', $this->host_id)
            ->where('status',1)->select();

        foreach ($modifyRule as $k => $v){
            $mrTmp['directory'] = $v['website_path'];

            if($v['file_protect'] == 1){
                $mrTmp['dynamic'] = true;
                $mrTmp['static'] = false;
                $mrTmp['other'] = false;
            }elseif($v['file_protect'] == 2){
                $mrTmp['dynamic'] = false;
                $mrTmp['static'] = true;
                $mrTmp['other'] = false;
            }elseif($v['file_protect'] == 3){
                $mrTmp['dynamic'] = true;
                $mrTmp['static'] = true;
                $mrTmp['other'] = false;
            }else{
                $mrTmp['dynamic'] = true;
                $mrTmp['static'] = true;
                $mrTmp['other'] = true;
            }

            $mrTmp['create'] = $v['create'] == 1 ? true : false;
            $mrTmp['edit'] = $v['modify'] == 1 ? true : false;
            $mrTmp['delete'] = $v['del'] == 1 ? true : false;

            $modifyRuleData[] = $mrTmp;
        }


        //防篡改排除规则
        $modifyExclueRule = db('host_exclude')->where('host_id', $this->host_id)
            ->where('illegal_modify',1)->select();


        foreach ($modifyExclueRule as $key => $val){
            $merTmp['content'] = $val['content'];
            if($val['type'] == 1){

                $merTmp['type'] = 'file';

            }elseif($val['type'] == 2){

                $merTmp['type'] = 'directory';

            }elseif($val['type'] == 3){

                $merTmp['type'] = 'process';

            }else{

                $merTmp['type'] = 'extension';
            }

            $merTmp['defense'] = false;
            $merTmp['tamper'] = true;
            $merTmp['create'] = $val['create'] == 1 ? true : false;
            $merTmp['edit'] = $val['modify'] == 1 ? true : false;
            $merTmp['del'] = $val['del'] == 1 ? true : false;

            $modifyExclueRuleData[] = $merTmp;
        }

        $defenseRule = db('defense_normal')->field('Mode, Content')->select();

        foreach ($defenseRule as $i => $item){
            $drTmp['mode'] = $item['Mode'] == 1 ? 'reject' : 'pass';
            $drTmp['rule'] = $item['Content'];

            $defenseRuleData[] = $drTmp;
        }

        $defenseExclueRule = db('host_exclude')->where('host_id', $this->host_id)
            ->where('auto_defense',1)->select();

        foreach ($defenseExclueRule as $ki => $vi){
            $derTmp['content'] = $vi['content'];
            if($vi['type'] == 1){

                $derTmp['type'] = 'file';

            }elseif($vi['type'] == 2){

                $derTmp['type'] = 'directory';

            }elseif($vi['type'] == 3){

                $derTmp['type'] = 'process';

            }else{

                $derTmp['type'] = 'extension';
            }

            $derTmp['defense'] = true;
            $derTmp['tamper'] = false;
            $derTmp['create'] = $vi['create'] == 1 ? true : false;
            $derTmp['edit'] = $vi['modify'] == 1 ? true : false;
            $derTmp['del'] = $vi['del'] == 1 ? true : false;

            $defenseExclueRuleData[] = $derTmp;
        }


        $return['TpRules'] = $modifyRuleData;//防篡改规则
        $return['TpWhites'] = $modifyExclueRuleData;//防篡改排除
        $return['AdWhites'] = $defenseExclueRuleData;//主动防御排除
        $return['AdRules'] = $defenseRuleData;//主动防御规则

        return $return;
    }

    /**
     * @name: 获取模块连接
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-09 13:50:35
     */
    private function getModuleConnect($module)
    {
        $ServerProxy = new service\ServerProxy();

        $return = $ServerProxy->getIp($module);

        if (empty($return))
        {
            return false;
        }

        $this->module_ip = $return['ip'];
        $this->module_port = $return['port'];
    }

    /**
     * @name: 获取虚拟ip
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-09 13:58:05
     */
    private function getPoxyConnect()
    {

        $ServerProxy = new service\ServerProxy();
        $return = $ServerProxy->getIp('proxy');

        if (empty($return))
        {
            return false;
        }

        $this->poxy_ip = $return['ip'];
        $this->poxy_port = $return['port'];
    }

    /**
     * @name: 获取主机id
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-09 14:09:23
     */
    private function getHostId ($hostkey)
    {
        $HostContact = new service\Host();

        $hostInfo = $HostContact->findData(['key' => $hostkey]);

        if(empty($hostInfo))
        {
            $this->setError($this->CODE_FAIL, '不存在该主机');
            return false;
        }

        $this->host_id = $hostInfo['id'];
        $this->group_id = $hostInfo['group_id'];
    }

    /**
     * @name: 检测模块状态
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-01-04 11:15:19
     */
    private function checkModule ($module)
    {
        $HostModuleRelation = new service\HostModuleRelation();
        $hostModule = $HostModuleRelation->findByHostId($this->host_id);

        if(empty($hostModule))
        {
            $this->setError($this->CODE_FAIL, '该主机不存在');
            return false;
        }

        if(!isset($hostModule[$module]))
        {
            $this->setError($this->CODE_FAIL, '该模块不存在');
            return false;
        }



        if($hostModule[$module] == 0)
        {
            $this->setError($this->CODE_FAIL, '该模块未授权开启');
            return false;

//            $moduleInfo = db('server_user_group_module sugm')
//                ->join('server_auth_module sam', 'sugm.module_id = sam.id')
//                ->where('module_key', $module)
//                ->where('group_id', $this->group_id)
//                ->field('sugm.id, total, used, sugm.etime')
//                ->find();
//
//            if(!$moduleInfo){
//                $this->setError($this->CODE_FAIL, '该用户组未授权此模块');
//                return false;
//            }elseif ($moduleInfo['total'] <= $moduleInfo['used']){
//                $this->setError($this->CODE_FAIL, '该用户组未此模块授权数量已满');
//                return false;
//            }elseif ($moduleInfo['etime'] != 0 && time() > $moduleInfo['etime']){
//                $this->setError($this->CODE_FAIL, '该用户组未此模块授权时间已到');
//                return false;
//            }else{
//                //开启模块
//                db('server_user_group_module')->where('id', $moduleInfo['id'])->setInc('used', 1);
//                db('host_module_relation')->where('id', $hostModule['id'])->update([$module => 1]);
//            }

        }

        return true;
    }

    /**
     * @name: 更新版本号
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-01-07 19:03:59
     */
    function updateVersion ($module, $version)
    {
        $HostLink = new service\HostLink;
        $HostLink->updateVersion($this->host_id, $module, $version);
    }
}